import GpContainer from "@/components/GpContainer";
import { GpTouchableView } from "@/components/GpTouchableView";
import { useNavigateEventChannel } from "@/hooks/useNavigateEventChannel";
import { useOptionSelect } from "@/hooks/useOptionSelect";
import { navigate } from "@/utils/navigation";
import { Picker, Popup, SafeArea } from "@taroify/core";
import { Text, View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import clsx from "clsx";
import { useEffect } from "react";
import { workModeOptions } from "../../enum-options";
import GpFontIcon from "@/components/GpFontIcon";
import { useSalaryPannel } from "./composables/useSalaryPannel";
import { EnumWorkMode, Industry, JobType, MemberResumeBaseEditRequest, Region } from "@/apis/endpoint/model";
import { isSetValue } from "@/utils/helper";
import { pageMapper } from "@/constants/pageMap";
import { useImmer } from "use-immer";
import { postMyEditjobintention } from "@/apis/endpoint/my";

interface ReceivedIntention {
  workMode: EnumWorkMode
  cityId: string
  cityName: string
  jobTypeId: number
  jobTypeName: string
  salaryMin: number
  salaryMax: number
  industryIds: number[]
  industryNames: string[]
}
type Draft = Omit<ReceivedIntention, "workMode" | "salaryMin" | "salaryMax">
export default function Index() {
  const { eventChannel } = useNavigateEventChannel()
  const {
    selects: workModeSelects,
    apply: workModeApply,
    handleItemTap: workModeTap,
    setSelectsValue: setWorkModeSelects
  } = useOptionSelect({
    availableOptions: workModeOptions,
    treatAll: false,
    rollbackSync: false,
    syncSelects() {
      workModeApply()
    },
  })
  const {
    salaryValue,
    openSalary,
    salaryColumns,
    closeSalaryPannel,
    openSalaryPannel,
    confirmSalary,
    setSalary
  } = useSalaryPannel()
  const [state, setState] = useImmer({ industryIds: [], industryNames: []} as unknown as Draft)
  useEffect(() => {
    eventChannel && eventChannel.once("receiveIntention", (data: ReceivedIntention) => {
      if (isSetValue(data.workMode)) {
        setWorkModeSelects([data.workMode])
      }
      if (data.salaryMin && data.salaryMax) {
        setSalary([data.salaryMin, data.salaryMax])
      }
      const patch: Partial<Draft> = {}
      if (data.cityId) {
        patch.cityId = data.cityId
        patch.cityName = data.cityName
      }
      if (data.jobTypeId) {
        patch.jobTypeId = data.jobTypeId
        patch.jobTypeName = data.jobTypeName
      }
      if (data.industryIds && data.industryNames.length > 0) {
        patch.industryIds = data.industryIds
        patch.industryNames = data.industryNames
      }
      setState(draft => {
        return {
          ...draft,
          ...patch
        }
      })
    })
  }, [])
  function openCitySelect() {
    const query = state.cityId ? { cityid: state.cityId } : null
    navigate(pageMapper.select.city, query, "navigateTo", {
      events: {
        chooseCity(city: Region) {
          setState(draft => {
            draft.cityId = city.id
            draft.cityName = city.name
          })
        }
      }
    })
  }
  function openJobSelect() {
    const query = state.jobTypeId ? { jobtypeid: state.jobTypeId } : null
    navigate(pageMapper.select.jobtype, query, "navigateTo", {
      events: {
        chooseJobType(data: JobType) {
          setState(draft => {
            draft.jobTypeId = data.id
            draft.jobTypeName = data.name
          })
        }
      }
    })
  }
  function openIndustrySelect() {
    const query = state.industryIds.length > 0 ? { industryids: state.industryIds.join(",") } : null
    navigate(pageMapper.select.industry, query, "navigateTo", {
      events: {
        chooseIndustry(data: Industry[]) {
          const ids: number[] = []
          const names: string[] = []
          data.forEach(item => {
            ids.push(item.id)
            names.push(item.name)
          })
          setState(draft => {
            draft.industryIds = ids
            draft.industryNames = names
          })
        }
      }
    })
  }
  async function handleSave() {
    if (workModeSelects.length <= 0) {
      Taro.showToast({
        title: "请选择工作类型"
      })
      return
    }
    if (!state.cityId) {
      Taro.showToast({
        title: "请选择工作城市"
      })
      return
    }
    if (!state.jobTypeId) {
      Taro.showToast({
        title: "请选择期望职位"
      })
      return
    }
    const params: MemberResumeBaseEditRequest = {
      workMode: workModeSelects[0],
      cityId: state.cityId,
      jobTypeId: state.jobTypeId
    }
    if (salaryValue?.length) {
      const [min, max] = salaryValue
      params.salaryMin = min * 1000
      params.salaryMax = max * 1000
    }
    if (state.industryIds.length > 0) {
      params.industryIds = state.industryIds
    }
    await postMyEditjobintention(params).send({loadingText: "保存中"})
    Taro.showToast({
      title: "保存成功",
      icon: "success"
    })
    navigate()
  }
  function renderActionPannels() {
    return (
      <View>
        {renderSalaryPannel()}
      </View>
    )
  }
  function renderSalaryPannel() {
    return (
      <Popup open={openSalary} rounded placement="bottom" onClose={closeSalaryPannel}>
        <Popup.Backdrop />
        <Picker
          value={salaryValue}
          title="薪资要求(月薪，单位:千元)"
          cancelText="取消"
          confirmText="确认"
          columns={salaryColumns}
          onCancel={closeSalaryPannel}
          onConfirm={confirmSalary}
        ></Picker>
      </Popup>
    )
  }
  return (
    <GpContainer className="bg-white">
      <View className="px-[32px] pt-[16px]">
        <View>
          <Text className="text-primary text-[48px] font-bold">求职意向</Text>
        </View>
        <Text className="inline-block mt-[28px] text-third text-[28px] leading-[36px]">
          根据求职意向为你推荐专属职位
        </Text>
        <View className="mt-[14px]">
          <View className="box-border py-[32px] border-b-2 border-solid border-b-[#EEEEEE] flex flex-row items-center justify-between">
            <Text className="text-primary text-[28px]">工作类型</Text>
            <View className="flex flex-nowrap flex-row items-center gap-[20px] justify-end">
              {
                workModeOptions.map(item => (
                  <GpTouchableView
                    key={item.value}
                    className={clsx(
                      "flex flex-row justify-center items-center box-border h-[64px] rounded-[16px] px-[40px]",
                      workModeSelects.includes(item.value)
                      ? "bg-theme text-white font-medium"
                      : "border-2 border-solid border-[#CED4DB] text-third"
                    )}
                    onClick={() => workModeTap(item)}
                  >
                    <Text className="text-[28px]">{item.label}</Text>
                  </GpTouchableView>
                ))
              }
            </View>
          </View>
          <View className="flex flex-col gap-[32px] pt-[48px] pb-[30px] border-b-2 border-solid border-b-[#EEEEEE]">
            <Text className="text-primary text-[28px]">工作城市</Text>
            <View className="flex flex-row justify-between items-center" onClick={openCitySelect}>
              <Text className={clsx("text-[32px]", state.cityId ? "text-primary font-bold" : "text-placeholder")}>
                {state.cityId ? state.cityName : "请选择工作城市"}
              </Text>
              <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder" />
            </View>
          </View>
          <View className="flex flex-col gap-[32px] pt-[48px] pb-[30px] border-b-2 border-solid border-b-[#EEEEEE]">
            <Text className="text-primary text-[28px]">期望职位</Text>
            <View className="flex flex-row justify-between items-center" onClick={openJobSelect}>
              <Text className={clsx("text-[32px]", state.jobTypeId ? "text-primary font-bold" : "text-placeholder")}>
                {state.jobTypeId ? state.jobTypeName : "请选择期望职位"}
              </Text>
              <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder" />
            </View>
          </View>
          <View className="flex flex-col gap-[32px] pt-[48px] pb-[30px] border-b-2 border-solid border-b-[#EEEEEE]">
            <Text className="text-primary text-[28px]">薪资要求</Text>
            <View className="flex flex-row justify-between items-center" onClick={openSalaryPannel}>
              <Text className={clsx("text-[32px]", salaryValue ? "text-primary font-bold" : "text-placeholder")}>
                {salaryValue ? `${salaryValue[0]}k~${salaryValue[1]}k` : "请选择薪资要求"}
              </Text>
              <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder" />
            </View>
          </View>
          <View className="flex flex-col gap-[32px] pt-[48px] pb-[30px] border-b-2 border-solid border-b-[#EEEEEE]">
            <Text className="text-primary text-[28px]">期望行业</Text>
            <View className="flex flex-row justify-between items-center" onClick={openIndustrySelect}>
              <Text className={clsx("text-[32px]", state.industryIds.length > 0 ? "text-primary font-bold" : "text-placeholder")}>
                {state.industryIds.length > 0 ? state.industryNames.join(",") : "请选择期望行业"}
              </Text>
              <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder" />
            </View>
          </View>
        </View>
      </View>
      <View className="fixed bottom-0 left-0 right-0 px-[32px] pb-[32px]">
        <GpTouchableView className="h-[80px] flex flex-row justify-center items-center bg-theme rounded-[64px] mt-[40px]" onClick={handleSave}>
          <Text className="text-white text-[32px]">保存</Text>
        </GpTouchableView>
        <SafeArea position="bottom" />
      </View>
      {renderActionPannels()}
    </GpContainer>
  )
}
